package org.charmsoft.generator;

import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.charmsoft.error.ReturnCode;
import org.charmsoft.error.StatusCode;
import org.charmsoft.files.DefaultWorkBookLoader;
import org.charmsoft.files.WorkBookLoader;
import org.charmsoft.tasks.GenerateTask;
import org.charmsoft.validation.ValidationUtils;
import org.charmsoft.validation.ValidationWrapper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.File;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
 * @ Author: Allen J L Chen
 * This Class is generator to generate target class.
 * ${DATE}
 **/
public class ExcelToArtifactGenerator implements Generator{
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelToArtifactGenerator.class);
    ExecutorService executorService = Executors.newFixedThreadPool(8);

    private File[] files;

    public ExcelToArtifactGenerator(File[] files) {
        this.files = files;
    }

    public StatusCode generate(File[] files) {
        StatusCode statusCode = new StatusCode();
        if(files == null) {
            statusCode.setMessage(String.valueOf(ReturnCode.valueOf(ReturnCode.CONVERTED.name())));
            return statusCode;
        }
        WorkBookLoader workBookLoader = new DefaultWorkBookLoader();

        Map<String, XSSFWorkbook> map = workBookLoader.load(files);

        ValidationWrapper validationWrapper = ValidationUtils.validateWorkbook(map);

        Map<String, XSSFWorkbook> validWorkbookMap = validationWrapper.getValidWorkbookMap();

        try {
            validWorkbookMap.forEach((name,workbook) -> {
                GenerateTask generateTask = new GenerateTask(name, workbook);
                executorService.submit(generateTask);
            });
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            statusCode.setMessage(e.getMessage());
        } finally {
            executorService.shutdown();
        }

        return statusCode;
    }

    @Override
    public StatusCode generate() {

        return generate(files);
    }
}
